package com.strongbj.iot.devices.dam.sub.dacai.response.coder;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.iot.devices.dam.sub.dacai.message.DaCaiMessage;
import com.strongbj.iot.devices.dam.sub.dacai.message.DaCaiMessageType;
import com.strongbj.iot.devices.dam.sub.dacai.response.IMessageCoder;

public class DaCaiMessageCoder implements IMessageCoder {
	private static Logger logger = LogManager.getLogger(DaCaiMessageCoder.class.getName());

	@Override
	public List<DaCaiMessage> decode(String datas) {
		List<DaCaiMessage> list = new ArrayList<>();
		logger.debug("收到屏幕命令数据:{}", datas);
		String[] messages = datas.split(DaCaiMessage.SYS_FOOTER + "|" + DaCaiMessage.SELF_FOOTER);
		try {
			logger.debug("---------------对接收到的屏幕命令拆包--------------");
			for (String msg : messages) {
				logger.debug("切分出的屏幕命令:{}", msg);
			}
			logger.debug("------------------------------------------------");
		} catch (Exception e) {
			logger.error(e);
		}
		for (int i = 0; i < messages.length; i++) {
			try {
				int systemIndex = messages[i].indexOf(DaCaiMessage.SYS_HEADER);
				systemIndex = systemIndex < 0 ? Integer.MAX_VALUE : systemIndex;
				int selfIndex = messages[i].indexOf(DaCaiMessage.SELF_HEADER);
				selfIndex = selfIndex < 0 ? Integer.MAX_VALUE : selfIndex;

				// 如果没有找到系统或自定义消息头，就忽略此消息
				if (systemIndex == Integer.MAX_VALUE && selfIndex == Integer.MAX_VALUE)
					continue;

				DaCaiMessage msg = new DaCaiMessage();
				if (systemIndex < selfIndex) {
					msg.setMessageType(DaCaiMessageType.System);
					if (messages[i].substring(2, 4).equals("B1")) {
						msg.setDatas(messages[i].substring(systemIndex + 6));
						msg.setCommand(messages[i].substring(systemIndex + 2, systemIndex + 6));
					} else {
						msg.setDatas(messages[i].substring(systemIndex + 4));
						msg.setCommand(messages[i].substring(systemIndex + 2, systemIndex + 4));
					}
				} else {
					msg.setMessageType(DaCaiMessageType.Self);
					msg.setDatas(messages[i].substring(selfIndex + 4));
					msg.setCommand(messages[i].substring(selfIndex + 2, selfIndex + 4));
				}
				list.add(msg);
			} catch (Exception e) {
				logger.error(e);
			}
		}
		return list;
	}
}
